package cn.hicard.auth.service.impl;

import java.security.MessageDigest;
import java.util.List;

import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.User;
import org.activiti.engine.impl.persistence.entity.UserEntity;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.hicard.auth.dao.UserRoleDao;
import cn.hicard.auth.dao.UserinfoDao;
import cn.hicard.auth.entity.MgUserRole;
import cn.hicard.auth.entity.MgUserinfo;
import cn.hicard.auth.service.UserinfoService;
import cn.hicard.auth.vo.LoginResult;
import cn.hicard.common.Constant;
import cn.hicard.core.Page;
import cn.hicard.core.PageResult;
import cn.hicard.core.Where;
import cn.hicard.util.DateHelp;

import com.sun.org.apache.xml.internal.security.utils.Base64;

/**
 * 用户信息管理业务接口实现
 * @author zhangy
 *
 */
@Service
public class UserinfoServiceImpl implements UserinfoService{


	private static final Logger logger = Logger.getLogger(Constant.LOG_FRAME);
	
	@Autowired
	private UserinfoDao userinfoDao;
	@Autowired
	private UserRoleDao userRoleDao;
	
	// 由activiti工作流支持提供，如果不注入则不会同步数据
	@Autowired(required=false)
	private IdentityService identityService;

	public void save(MgUserinfo userinfo)throws Exception{
		// 检查用户名是否存在
		if(userinfoDao.existLoginid(userinfo.getLoginid())){
			throw new Exception("登录名loginid已经存在");
		}
		// 保存
		userinfo.setAdddatetime(DateHelp.dateTime());
		userinfo.setModdatetime("");
		userinfoDao.save(userinfo);	
		
		// 同步activiti用户表
		if(identityService != null){
			UserEntity user = new UserEntity();
			user.setId(userinfo.getLoginid());
			user.setFirstName(userinfo.getRealname());
			user.setEmail(userinfo.getEmail());
			user.setPassword(userinfo.getPassword());
			List<User> users = identityService.createUserQuery().userId(userinfo.getLoginid()).list();
			if(users.size()>0){
				// 如果存在，则需要拿出版本号，否则版本号为0时会被认为是新增操作
				int next = ((UserEntity)users.get(0)).getRevision();
				user.setRevision(next);
			}
			identityService.saveUser(user);	
			logger.debug("成功从表mg_userinfo同步[保存]用户数据[loginid="+userinfo.getLoginid()+"]到activiti用户表act_id_user");
		}		
	}
	
	public void update(MgUserinfo userinfo)throws Exception{
		userinfo.setModdatetime(DateHelp.dateTime());
		userinfoDao.update(userinfo);
		
		// 同步activiti用户表
		if(identityService != null){
			UserEntity user = new UserEntity();
			user.setId(userinfo.getLoginid());
			user.setFirstName(userinfo.getRealname());
			user.setEmail(userinfo.getEmail());
			user.setPassword(userinfo.getPassword());
			List<User> users = identityService.createUserQuery().userId(userinfo.getLoginid()).list();
			if(users.size()>0){
				// 如果存在，则需要拿出版本号，否则版本号为0时会被认为是新增操作
				int next = ((UserEntity)users.get(0)).getRevision();
				user.setRevision(next);
			}
			identityService.saveUser(user);
			logger.debug("成功从表mg_userinfo同步[更新]用户数据[loginid="+userinfo.getLoginid()+"]到activiti用户表act_id_user");
		}
	}
	
	public void delete(int pkUserinfo)throws Exception{
		// 删除用户之前，先删除与用户相关联的[用户*角色]
		userRoleDao.deleteByUser(pkUserinfo);
		
		// 再删除用户本身
		MgUserinfo userinfo = userinfoDao.getByPk(pkUserinfo);
		userinfoDao.delete(pkUserinfo);
		
		// 同步activiti用户表	
		if(identityService != null){
			identityService.deleteUser(userinfo.getLoginid());
			logger.debug("成功从表mg_userinfo同步[删除]用户数据[loginid="+userinfo.getLoginid()+"]到activiti用户表act_id_user");
		}
	}
	
	public MgUserinfo getByPk(int pkUserinfo)throws Exception{
		return userinfoDao.getByPk(pkUserinfo);
	}

	@Override
	public PageResult<MgUserinfo> search(Where where, Page page)
			throws Exception {
		return userinfoDao.search(where, page);
	}

	@Override
	public MgUserinfo getByLoginid(String loginid) throws Exception {
		return userinfoDao.getByLoginid(loginid);
	}

	@Override
	public boolean existLoginid(String loginid) throws Exception {
		return userinfoDao.existLoginid(loginid);
	}

	@Override
	public LoginResult login(String loginid, String password, String usertype) throws Exception {
		LoginResult lr = new LoginResult();
		MgUserinfo userinfo = getByLoginid(loginid);

		MessageDigest md = MessageDigest.getInstance("MD5");
		password = Base64.encode(md.digest(password.getBytes()));
		
		if(userinfo == null || !password.equals(userinfo.getPassword())){
			lr.message = "用户名或密码不正确";
			lr.result = false;
			return lr;
		}
		if("0".equals(userinfo.getEnabled())){
			lr.message = "该帐号已被禁用，无法使用，请找管理员解禁";
			lr.result = false;
			return lr;
		}
		if("1".equals(usertype) && "1".equals(userinfo.getUsertype())){
			lr.message = "该帐号为普通用户，无法登录管理员界面";
			lr.result = false;
			return lr;
		}
		
		lr.message = "OK";
		lr.result = true;
		lr.userinfo = userinfo;
		return lr;
	}

	@Override
	public List<MgUserinfo> getAll() throws Exception {
		return userinfoDao.getAll();
	}

	@Override
	public void saveUserRole(int pkUserinfo, List<MgUserRole> urlist) throws Exception {
		// 将原有的用户的角色分本配清除
		userRoleDao.deleteByUser(pkUserinfo);
		
		// 再保存新分配的
		userRoleDao.saveUserRoles(urlist);
	}

	@Override
	public List<Integer> findOwnRolePks(int pkUserinfo) throws Exception {
		return userRoleDao.findOwnRolePks(pkUserinfo);
	}
	
	
}
